//
//  PTStudentLifeServiceViewController.m
//  PlanTech
//  生活服务
//  Created by ruifeng song on 2018/7/10.
//  Copyright © 2018年  androidlongs. All rights reserved.
//

#import "PTStudentLifeServiceViewController.h"
#import "PTStuLifeServiceListCell.h"
#import "PTStuLifeServiceHeaderBackView.h"
#import "PTStuLifeServiceReleaseViewController.h"
#import "PTStuLifeServiceMyReleaseViewController.h"
#import "PTStuLifeServiceMyPartJobViewController.h"
#import "PTStuLifeServiceDemandDetailViewController.h"

#import "PTCoreManager.h"
#import "PTCoreManager+LifeService.h"
#import "PTCoreObject+LifeService.h"
#import "SINALoginViewController.h"
#import "SINANavLoginViewController.h"

@interface PTStudentLifeServiceViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,LifeServiceHeaderViewDelegate>
{
    NSInteger currentPage;
    
    int expressPageNum;
    int printPageNum;
    int buyMealPageNum;
    int hotboomPageNum;
    
    CGFloat historyY;
    
    BOOL isTop;
}
@property(nonatomic,strong) UIView * backContentView ;
@property(nonatomic,assign)BOOL isRefreshData;   //是否正在加载
@property(nonatomic,assign) int currentPageNum;   //请求数据页
@property(nonatomic,strong)PTStuLifeServiceHeaderBackView * headerBackView;
@property(nonatomic,strong)UITableView * expressTableView;   //代取快递
@property(nonatomic,strong)UITableView * printTableView;     //打印复印
@property(nonatomic,strong)UITableView * buyMealTableView;   //捎饭带饭
@property(nonatomic,strong)UITableView * hotboomTableView;   //超市代购

@property(nonatomic,strong)UIScrollView * lifeServiceScrolView;

@property(nonatomic,strong)NSMutableArray<LifeServiceListModel *> *expressArray;
@property(nonatomic,strong)NSMutableArray<LifeServiceListModel *> *printArray;
@property(nonatomic,strong)NSMutableArray<LifeServiceListModel *> *buyMealArray;
@property(nonatomic,strong)NSMutableArray<LifeServiceListModel *> *hotboomArray;

@property(nonatomic,assign)PTLifeServiceType serviceType;   //服务类型

@end

@implementation PTStudentLifeServiceViewController


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

-(NSMutableArray *)expressArray
{
    if (!_expressArray) {
        
        _expressArray = [NSMutableArray array];
    }
    return _expressArray;
}

-(NSMutableArray *)printArray
{
    if (!_printArray) {
        
        _printArray = [NSMutableArray array];
    }
    return _printArray;
}

-(NSMutableArray *)buyMealArray
{
    if (!_buyMealArray) {
        
        _buyMealArray = [NSMutableArray array];
    }
    return _buyMealArray;
}

-(NSMutableArray *)hotboomArray
{
    if (!_hotboomArray) {
        
        _hotboomArray = [NSMutableArray array];
    }
    return _hotboomArray;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.view.backgroundColor = BaseViewBackgroundColor;
    
    self.view.layer.backgroundColor = [[UIColor colorWithRed:237.0f/255.0f green:237.0f/255.0f blue:237.0f/255.0f alpha:1.0f] CGColor];
    self.view.alpha = 1;
    
    self.serviceType = PTLifeService_ExpressType;
    
    self.isRefreshData = NO;
    
    self.currentPageNum = [self getCurrentRequestPageWithRefresh:YES];
    
    [self createView];
    
    [self requestData];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(requestData) name:kPT_Global_Notification_RefreshLifeServiceList object:nil];
}

-(void)createView
{
    self.backContentView = [[UIView alloc]initWithFrame:CGRectMake(0,0,ScreenWidth,ScreenHeight)];

    self.backContentView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.backContentView];
    
    //头部底图
    [self.backContentView addSubview:self.headerBackView];
    
    [self updateHeaderBackImageWithTag:1];
    
    _lifeServiceScrolView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,TOP_HEIGHT + 54,ScreenWidth,ScreenHeight - (TOP_HEIGHT) - 54)];
    _lifeServiceScrolView.pagingEnabled = YES;
    _lifeServiceScrolView.contentSize = CGSizeMake(ScreenWidth * 4, ScreenHeight - (TOP_HEIGHT) - 54);
    _lifeServiceScrolView.delegate = self;
    _lifeServiceScrolView.showsHorizontalScrollIndicator = NO;
    [self.backContentView addSubview:_lifeServiceScrolView];
    
    self.expressTableView = [self createTableViewWithPageTag:0];
    [_lifeServiceScrolView addSubview:self.expressTableView];
    
    self.printTableView = [self createTableViewWithPageTag:1];
    [_lifeServiceScrolView addSubview:self.printTableView];
    
    self.buyMealTableView = [self createTableViewWithPageTag:2];
    [_lifeServiceScrolView addSubview:self.buyMealTableView];
    
    self.hotboomTableView = [self createTableViewWithPageTag:3];
    [_lifeServiceScrolView addSubview:self.hotboomTableView];
    
    
    [self.headerBackView.releaseButton addTarget:self action:@selector(onClickReleaseButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.headerBackView.myReleaseButton addTarget:self action:@selector(onClickMyReleaseButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.headerBackView.myPartJobButton addTarget:self action:@selector(onClickMyPartJobButton:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)updateHeaderBackImageWithTag:(NSInteger)pageTag
{
    
    NSString * imgStr = @"";
    //判断是否是X
    if (IS_IPHONE_X) {
        
        imgStr = [NSString stringWithFormat:@"lifeservice_headerbackimg%ldX",pageTag];
    }
    else
    {
        imgStr = [NSString stringWithFormat:@"lifeservice_headerbackimg%ld",pageTag];
        
    }
    
    [self.headerBackView.headerBackImageView setImage:[UIImage imageNamed:imgStr]];
}

-(PTStuLifeServiceHeaderBackView *)headerBackView
{
    if (_headerBackView ==nil) {
        
        _headerBackView = [[PTStuLifeServiceHeaderBackView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 109 + (TOP_HEIGHT))];
        _headerBackView.backgroundColor = [UIColor clearColor];
        _headerBackView.headerView.delegate = self;
    }
    return _headerBackView;
}

-(UITableView *)createTableViewWithPageTag:(NSInteger)pageTag
{
    UITableView * tv = [[UITableView alloc]initWithFrame:CGRectMake(ScreenWidth * pageTag, 0, ScreenWidth, ScreenHeight - (TOP_HEIGHT) - 54)];
    tv.delegate = self;
    tv.dataSource = self;
    tv.separatorStyle = UITableViewCellSeparatorStyleNone;
    tv.backgroundColor = [UIColor clearColor];
    
    WeakSelf;
    tv.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        if (weakSelf.isRefreshData) {
            
            return ;
        }
        
        //下拉刷新
        weakSelf.currentPageNum = [weakSelf getCurrentRequestPageWithRefresh:YES];
        [weakSelf requestData];
        
    }];
    
    tv.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        if (weakSelf.isRefreshData) {
            
            return ;
        }
        //上拉加载
        weakSelf.currentPageNum = [weakSelf getCurrentRequestPageWithRefresh:NO];
        [weakSelf requestData];
    }];
    
    return tv;
}

-(int)getCurrentRequestPageWithRefresh:(BOOL)isHeaderRefreshing
{
    switch (self.serviceType) {
        case PTLifeService_ExpressType:
        {
            if (isHeaderRefreshing) {
                expressPageNum = 1;
            }
            else
            {
                expressPageNum++;
            }
            return expressPageNum;
        }
            break;
        case PTLifeService_PrintType:
        {
            if (isHeaderRefreshing) {
                printPageNum = 1;
            }
            else
            {
                printPageNum ++;
            }
            return printPageNum;
        }
            
            break;
        case PTLifeService_BuyMealType:
        {
            if (isHeaderRefreshing) {
                buyMealPageNum = 1;
            }
            else
            {
                buyMealPageNum ++;
            }
            return buyMealPageNum;
        }
            
            break;
        case PTLifeService_HotboomType:
        {
            if (isHeaderRefreshing) {
                hotboomPageNum = 1;
            }
            else
            {
                hotboomPageNum ++;
            }
            return hotboomPageNum;
        }
            break;
    }
    return 1;
}

-(void)requestData
{
    [self requestLifeServcieListDataWithType:self.serviceType pageNum:self.currentPageNum];
}

//根据服务类型获取相应的数据
-(void)requestLifeServcieListDataWithType:(PTLifeServiceType)type pageNum:(NSInteger)pageNum
{
    self.isRefreshData = YES;
    
    SINAUserModel *userModel = [[SINACommonUserHelper share]getUserModel];
    
    WeakSelf;
    [[PTCoreManager shareInstance]performGetLifeServiceListWithType:type universityId:userModel.universityid page:pageNum num:10 Completion:^(id _Nullable retObject, NSError * _Nullable retError) {
        
        weakSelf.isRefreshData = NO;
        
        DLog(@"retObject ====  %@ , type = %ld, pageNum = %ld",retObject,type,pageNum);
        
        if (retObject) {
            
            if ([retObject isKindOfClass:[PTMJsonResult class]]) {
                
            }
            else if ([retObject isKindOfClass:[NSArray class]])
            {
                [weakSelf ChangeResponseDataWithArray:retObject];
            }
        }
        else
        {
            //请求失败
        }
    }];
}

-(void)ChangeResponseDataWithArray:(NSArray *)obj
{
    //更新列表
    switch (self.serviceType) {
        case PTLifeService_ExpressType:
        {
            if (self.currentPageNum ==1) {
                [self.expressArray removeAllObjects];
                [self.expressTableView.mj_header endRefreshing];
                [self.expressTableView.mj_footer resetNoMoreData];
            }
            else
            {
                [self.expressTableView.mj_footer endRefreshing];
            }
            
            [self.expressArray addObjectsFromArray:obj];
            [self.expressTableView reloadData];
            
            if (obj.count<10) {
                //没有更多数据了
                [self.expressTableView.mj_footer endRefreshingWithNoMoreData];
            }
           
        }
            break;
        case PTLifeService_PrintType:
        {
            if (self.currentPageNum ==1) {
                [self.printArray removeAllObjects];
                [self.printTableView.mj_header endRefreshing];
                [self.printTableView.mj_footer resetNoMoreData];
            }
            else
            {
                [self.printTableView.mj_footer endRefreshing];
            }
            
            [self.printArray addObjectsFromArray:obj];
            [self.printTableView reloadData];
            
            if (obj.count<10) {
                [self.printTableView.mj_footer endRefreshingWithNoMoreData];
            }
           
        }
            break;
        case PTLifeService_BuyMealType:
        {
            if (self.currentPageNum ==1) {
                [self.buyMealArray removeAllObjects];
                [self.buyMealTableView.mj_header endRefreshing];
                [self.buyMealTableView.mj_footer resetNoMoreData];
            }
            else
            {
                [self.buyMealTableView.mj_footer endRefreshing];
            }
            [self.buyMealArray addObjectsFromArray:obj];
            [self.buyMealTableView reloadData];
            
            if (obj.count <10) {
                [self.buyMealTableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
            break;
        case PTLifeService_HotboomType:
        {
            if (self.currentPageNum==1) {
                [self.hotboomArray removeAllObjects];
                [self.hotboomTableView.mj_header endRefreshing];
                [self.hotboomTableView.mj_footer resetNoMoreData];
            }
            else
            {
                [self.hotboomTableView.mj_footer endRefreshing];
            }
            [self.hotboomArray addObjectsFromArray:obj];
            [self.hotboomTableView reloadData];
            
            if (obj.count<10) {
                [self.hotboomTableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
            break;
    }
}

#pragma mark -UITableViewDelegate & UITableViewDataSource

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * const LifeServiceListCellIdentifier = @"LifeServiceListCell";
    
    PTStuLifeServiceListCell * lifeServiceListCell = [tableView dequeueReusableCellWithIdentifier:LifeServiceListCellIdentifier];
    if (lifeServiceListCell == nil) {
        lifeServiceListCell = [[PTStuLifeServiceListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:LifeServiceListCellIdentifier];
        lifeServiceListCell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    switch (self.serviceType) {
        case PTLifeService_ExpressType:
            [lifeServiceListCell updateLifeServiceListCellWith:[self.expressArray objectAtIndex:indexPath.row]];
            break;
        case PTLifeService_PrintType:
            [lifeServiceListCell updateLifeServiceListCellWith:[self.printArray objectAtIndex:indexPath.row]];
            break;
        case PTLifeService_BuyMealType:
            [lifeServiceListCell updateLifeServiceListCellWith:[self.buyMealArray objectAtIndex:indexPath.row]];
            break;
        case PTLifeService_HotboomType:
            [lifeServiceListCell updateLifeServiceListCellWith:[self.hotboomArray objectAtIndex:indexPath.row]];
            break;
    }
    
    return lifeServiceListCell;
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (self.serviceType) {
        case PTLifeService_ExpressType:
            return self.expressArray.count;
            break;
        case PTLifeService_PrintType:
            return self.printArray.count;
            break;
        case PTLifeService_BuyMealType:
            return self.buyMealArray.count;
            break;
        case PTLifeService_HotboomType:
            return self.hotboomArray.count;
            break;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    LifeServiceListModel * listModel = nil;
    
    switch (self.serviceType) {
        case PTLifeService_ExpressType:
            listModel= [self.expressArray objectAtIndex:indexPath.row];
            break;
        case PTLifeService_PrintType:
            listModel= [self.printArray objectAtIndex:indexPath.row];
            break;
        case PTLifeService_BuyMealType:
            listModel= [self.buyMealArray objectAtIndex:indexPath.row];
            break;
        case PTLifeService_HotboomType:
            listModel= [self.hotboomArray objectAtIndex:indexPath.row];
            break;
    }
    
    PTStuLifeServiceDemandDetailViewController * lifeServiceDemandDetailViewController = [[PTStuLifeServiceDemandDetailViewController alloc]init];
    lifeServiceDemandDetailViewController.userUUID = listModel.userUUID;
    lifeServiceDemandDetailViewController.serviceUUID = listModel.serviceUUID;
    [lifeServiceDemandDetailViewController setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:lifeServiceDemandDetailViewController animated:YES];
}

#pragma mark --
#pragma mark --  UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    CGFloat pageWidth = self.lifeServiceScrolView.frame.size.width;
    
    int pageIndex = floor((self.lifeServiceScrolView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    
    if (pageIndex == currentPage) {
        
        return;
    }
    currentPage = pageIndex;
    
    [self updateHeaderBackImageWithTag:currentPage + 1];
    
    [self.headerBackView updateUnderlineLocationWithTag:currentPage];
    
    self.serviceType = currentPage + 8;
    
    [self requestData];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    historyY = scrollView.contentOffset.y;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    CGFloat orginY = 0;
    
    switch (self.serviceType) {
        case PTLifeService_ExpressType:
        {
            orginY = self.expressTableView.contentOffset.y;
            
            if (self.expressTableView.contentSize.height <=(ScreenHeight - (TOP_HEIGHT) - 54)) {
                
                [self showTopBackView];
                
                return;
            }
        }
            break;
        case PTLifeService_PrintType:
        {
            orginY = self.printTableView.contentOffset.y;
            if (self.printTableView.contentSize.height <=(ScreenHeight - (TOP_HEIGHT) - 54)) {
                
                [self showTopBackView];
                
                return;
            }
        }
            break;
        case PTLifeService_BuyMealType:
        {
            orginY = self.buyMealTableView.contentOffset.y;
            if (self.buyMealTableView.contentSize.height <=(ScreenHeight - (TOP_HEIGHT) - 54)) {
                
                [self showTopBackView];
                
                return;
            }
        }
            break;
        case PTLifeService_HotboomType:
        {
            orginY = self.hotboomTableView.contentOffset.y;
            if (self.hotboomTableView.contentSize.height <=(ScreenHeight - (TOP_HEIGHT) - 54)) {
            
                [self showTopBackView];
                
                return;
            }
        }
            break;
    }

    if (scrollView.contentOffset.y<historyY) {
     
        if (!isTop) {
            return;
        }
        
        if (orginY < -10) {
            
            [self showTopBackView];
        }
        
    } else if (scrollView.contentOffset.y>historyY) {
     
        if (orginY>0 && orginY < 55) {
        
            isTop = NO;
            
            [self.backContentView setFrame:CGRectMake(0, -orginY, ScreenWidth, ScreenHeight)];
            [self.headerBackView setFrame:CGRectMake(0, 0, ScreenWidth, TOP_HEIGHT + 109 - orginY)];
            [self.headerBackView.maskingView setFrame:CGRectMake(0, 0, ScreenWidth, self.headerBackView.height)];
            [self.headerBackView.headerBackImageView setFrame:CGRectMake(0, 0, ScreenWidth, self.headerBackView.height)];
            
            if (orginY >30) {
                
                [UIView animateWithDuration:0.5 animations:^{
                   
                    self.headerBackView.releaseButton.alpha = 0;
                    self.headerBackView.myPartJobButton.alpha = 0;
                    self.headerBackView.myReleaseButton.alpha = 0;
                }];
            }
            
        }
        else if (orginY > 55)
        {
            if (!isTop) {
                
                [self.backContentView setFrame:CGRectMake(0, -55, ScreenWidth, ScreenHeight)];
                [self.headerBackView setFrame:CGRectMake(0, 0, ScreenWidth, TOP_HEIGHT + 109 - 55)];
                [self.headerBackView.maskingView setFrame:CGRectMake(0, 0, ScreenWidth, self.headerBackView.height)];
                [self.headerBackView.headerBackImageView setFrame:CGRectMake(0, 0, ScreenWidth, self.headerBackView.height)];
                
                isTop = YES;
            }
           
        }
    }
}

-(void)showTopBackView
{
    isTop = NO;
    
    [UIView animateWithDuration:0.5 animations:^{
        
        [self.backContentView setFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        [self.headerBackView setFrame:CGRectMake(0, 0, ScreenWidth, TOP_HEIGHT + 109)];
        [self.headerBackView.headerBackImageView setFrame:CGRectMake(0, 0, ScreenWidth, self.headerBackView.height)];
        [self.headerBackView.maskingView setFrame:CGRectMake(0, 0, ScreenWidth, self.headerBackView.height)];
        
        self.headerBackView.releaseButton.alpha = 1;
        self.headerBackView.myPartJobButton.alpha = 1;
        self.headerBackView.myReleaseButton.alpha = 1;
        
    }];
}

#pragma mark 头部按钮点击事件

//点击添加发布事件
-(void)onClickReleaseButton:(id)sender
{
    PTStuLifeServiceReleaseViewController *lifeServiceReleaseViewController = [[PTStuLifeServiceReleaseViewController alloc]init];
    [lifeServiceReleaseViewController setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:lifeServiceReleaseViewController animated:YES];
}

//跳转到我的发布页面
-(void)onClickMyReleaseButton:(id)sender
{
    SINAUserModel *userModel = [[SINACommonUserHelper share]getUserModel];
    
    if (userModel.userUid==nil||[userModel.userUid isEqualToString:@""]) {
        //登录页面
        SINALoginViewController *rootViewControll = [[SINALoginViewController alloc]init ];
        SINANavLoginViewController *homeController = [[SINANavLoginViewController alloc] initWithRootViewController:rootViewControll];
        [self restoreRootViewController:homeController];
        
    } else {
        
        PTStuLifeServiceMyReleaseViewController * lifeServiceMyReleaseViewController = [[PTStuLifeServiceMyReleaseViewController alloc]init];
        [lifeServiceMyReleaseViewController setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:lifeServiceMyReleaseViewController animated:YES];
    }
}

//跳转到我的兼职页面
-(void)onClickMyPartJobButton:(id)sender
{
    PTStuLifeServiceMyPartJobViewController * lifeServiceMyPartJobViewController = [[PTStuLifeServiceMyPartJobViewController alloc]init];
    [lifeServiceMyPartJobViewController setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:lifeServiceMyPartJobViewController animated:YES];
}

- (void)restoreRootViewController:(UIViewController *)rootViewController
{
    typedef void (^Animation)(void);
    UIWindow* window = self.view.window;
    
    rootViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    Animation animation = ^{
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        window.rootViewController = rootViewController;
        [UIView setAnimationsEnabled:oldState];
    };
    
    [UIView transitionWithView:window
                      duration:0.5f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:animation
                    completion:nil];
}

#pragma mark LifeServiceHeaderViewDelegate Method
-(void)didSelectedHeaderMenuItemIndex:(NSInteger)itemIndex
{
    if (itemIndex == currentPage) {
        
        return;
    }
    currentPage = itemIndex;
    
    [self updateHeaderBackImageWithTag:currentPage + 1];
    
    [self.lifeServiceScrolView setContentOffset:CGPointMake(ScreenWidth * itemIndex, 0) animated:YES];
    
    [self.headerBackView updateUnderlineLocationWithTag:currentPage];
    
    self.serviceType = currentPage + 8;
    
    [self requestData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
